﻿using System;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;

namespace TvHeadend.Api
{
    public class Client : IDisposable
    {
	    private readonly string _server;

	    private readonly WebClient _client;

	    public Client(string server, string username, string password)
	    {
		    _server = server;

			_client = new WebClient();
			_client.Credentials = new NetworkCredential(username, password);
	    }

		public MuxList MuxList()
		{
			_client.Headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			_client.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
			_client.Headers["Accept-Language"] = "en-US,en;q=0.8,nl;q=0.6";

			string apiUrl = _server + "/api/mpegts/mux/grid?start=0&limit=9999999999";
			var response = _client.DownloadString(apiUrl);
			var muxList = JsonConvert.DeserializeObject<MuxList>(response);
			if(muxList.Muxes != null)
				muxList.Muxes = muxList.Muxes.OrderBy(m => m.ServiceName).ToList();
			return muxList;
		}

	    public void Dispose()
	    {
		    if (_client != null)
			    _client.Dispose();
	    }

		public NetworkList NetworkList()
		{
			_client.Headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			_client.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
			_client.Headers["Accept-Language"] = "en-US,en;q=0.8,nl;q=0.6";

			string apiUrl = _server + "/api/idnode/load?class=mpegts_network&enum=1&query=";
			var response = _client.DownloadString(apiUrl);
			var networkList = JsonConvert.DeserializeObject<NetworkList>(response);
			return networkList;
		}

	    public void MuxCreate(string network, string serviceName, string url, string @interface)
	    {
			_client.Headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
		    _client.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
		    _client.Headers["Accept-Language"] = "en-US,en;q=0.8,nl;q=0.6";

		    string test =
			    string.Format(@"{3}'enabled':true,'initscan':false,'iptv_url':'{0}','iptv_interface':'{1}','iptv_atsc':false,'iptv_svcname':'{2}','charset':''{4}", url, @interface, serviceName, "{", "}").Replace("'", "\"");

		    var response = _client.UploadString(_server + "/api/mpegts/network/mux_create", "POST", string.Format("uuid={0}&conf={1}", network.Replace("-", ""), Uri.EscapeDataString(test)));
	    }

		public ChannelList ChannelList()
		{
			_client.Headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			_client.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
			_client.Headers["Accept-Language"] = "en-US,en;q=0.8,nl;q=0.6";

			string apiUrl = _server + "/api/channel/grid?start=0&limit=9999999999";
			var response = _client.DownloadString(apiUrl);
			var channelList = JsonConvert.DeserializeObject<ChannelList>(response);
			return channelList;
		}

		public void SetChannelNumber(string id, int number)
		{
			_client.Headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			_client.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
			_client.Headers["Accept-Language"] = "en-US,en;q=0.8,nl;q=0.6";

			string request = string.Format("[{2}\"number\":{0},\"uuid\":\"{1}\"{3}]", number, id, "{", "}");
			var response = _client.UploadString(_server + "/api/idnode/save", "POST", string.Format("node={0}", Uri.EscapeDataString(request)));
		}

		public NodeList Node(string id)
		{
			_client.Headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			_client.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
			_client.Headers["Accept-Language"] = "en-US,en;q=0.8,nl;q=0.6";

			string apiUrl = _server + "/api/idnode/load";
			var response = _client.UploadString(apiUrl, "POST", string.Format("uuid={0}", id));
			var nodeList = JsonConvert.DeserializeObject<NodeList>(response);
			return nodeList;
		}

		public ServiceList ServiceList()
		{
			_client.Headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			_client.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
			_client.Headers["Accept-Language"] = "en-US,en;q=0.8,nl;q=0.6";

			string apiUrl = _server + "/api/mpegts/service/grid?start=0&limit=9999999999";
			var response = _client.UploadString(apiUrl, "POST", "start=0&limit=9999999999&sort=svcname&dir=ASC");
			var serviceList = JsonConvert.DeserializeObject<ServiceList>(response);
			return serviceList;
		}
    }
}
